
import axios from 'axios'
import qs from 'qs'
import router from '@/router/index.js'
import { Modal, message } from 'ant-design-vue'
/* import sysConfig from '@/config/index' */
/* import { convertUrl } from './apiAdaptive' */

// 定义一个重新登录弹出窗的变量
const loginBack = ref(false)
// 创建 axios 实例
const service = axios.create({
	baseURL: '', // api base_url
	timeout: 5000 // 请求超时时间
})
// 开关，是否使用配置文件中配置的接口地址
const switch1 = config.switch
let baseUrl = import.meta.env.VITE_API_BASEURL
if (switch1) {
	// 开关开启，替换接口地址
	baseUrl = config.baseUrl
}

// HTTP request 拦截器
service.interceptors.request.use(
	(config) => {
		config.headers['Content-Type'] = 'application/x-www-form-urlencoded'


		/* 	if (!sysConfig.REQUEST_CACHE && config.method === 'get') {
				config.params = config.params || {}
				config.params._ = new Date().getTime()
			}
			Object.assign(config.headers, sysConfig.HEADERS) */
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)


// HTTP response 拦截器
service.interceptors.response.use(
	(response) => {
		// 配置了blob，不处理直接返回文件流
		/* if (response.config.responseType === 'blob') {
			if (response.status === 200) {
				return response
			} else {
				message.warning('文件下载失败或此文件不存在')
				return
			}
		} */

		let url = response.config.url

		// 过滤掉获取验证码的接口
		if (url.includes('/GetValidateCodeStr')) {
			return Promise.resolve(response)
		} else {

			const data = response.data
			const result = data.Result
			if (!result) {
				if (data.ResultMsg === '未登录') {
					message.error(data.ResultMsg)
					localStorage.removeItem('userInfo')
					localStorage.removeItem('UUID')
					localStorage.removeItem('MgrModules')
					router.replace('/login')
					return Promise.reject(data.ResultMsg)
				}
				message.error(data.ResultMsg)
				return Promise.reject(data.ResultMsg)
			}
			return Promise.resolve(data)
		}

	},
	(error) => {
		if (error) {
			console.log(error)
			let { response } = error
			if (response) {
				message.error(response.data)
				return Promise.reject(response.data)
			}
			message.error(error.message)
			return Promise.reject(error.message)
		}
	}
)

// 适配器, 用于适配不同的请求方式
export const baseRequest = (url, value = {}, method = 'post', options = {}) => {
	url = baseUrl + url
	if (method === 'post') {
		return service.post(url, value, options)
	} else if (method === 'get') {
		return service.get(url, { params: value, ...options })
	} else if (method === 'formdata') {
		// form-data表单提交的方式
		return service.post(url, qs.stringify(value), {
			headers: {
				'Content-Type': 'multipart/form-data'
			},
			...options
		})
	} else {
		// 其他请求方式，例如：put、delete
		return service({
			method: method,
			url: url,
			data: value,
			...options
		})
	}
}
export default service
